﻿//指定站点的图片获取
var request = require('request'),
    https = require('https'),
    params = require("./initParams.js");
    getAndSaveFile = require("./fileGetAndSave.js");
    Log = require("./Log.js");

function searchSite(url) {
    Log.info("站点请求地址：" + url);
    request({
        headers: params.reqHead,
        url: url,
        method: 'GET',
        gzip: true
    }, function (err, res, body) {
        if (err) {
            Log.error("请求失败：" + url)
            Log.error('[ERROR]Collection' + err);
            return;
        }

        var obj = JSON.parse(body);
        var postListObj = obj.post_list;

        if (!obj || !postListObj) {
            Log.info("获取返回失败：" + url);
        }

        Log.info("站点页postObj数量：" + postListObj.length);

        for (var j = 0; j < postListObj.length; j++) {

            var imageLists = postListObj[j].images;

            if (!imageLists) return;

            Log.info("postObj-" + postListObj[j].post_id + "img数量：" + imageLists.length);

            for (var i = 0; i < imageLists.length; i++) {
                var img_id = imageLists[i].img_id;
                var user_id = imageLists[i].user_id;

                var fileName = img_id + "-" + user_id + ".jpg";
                var img_url = "https://photo.tuchong.com/" + user_id + "/f/" + img_id + ".jpg";

                getAndSaveFile(img_url, params.savePath, fileName);

            }
        }
    });
}

/**
 * 循环获取标签页
 */
function imgFlowGet() {
    Log.info("站点搜索开始");
    var pageBegin = params.reqParam.pageBegin;
    var pageEnd = params.reqParam.pageEnd;
    var site_id = params.reqParam.site_id;
    var count = params.reqParam.count;
    var order = params.reqParam.order;
    var before_timestamp = params.reqParam.before_timestamp;

    if (pageBegin < 0) pageBegin = 1;
    if (pageEnd < pageBegin) pageEnd = pageBegin + 1;
    if (count < 0) count = 1;

    for (var i = pageBegin; i < pageEnd; i++) {
        var post_url = "https://tuchong.com/rest/2/sites/" + site_id + "/posts?page=" + i + "&count=" + count + "&before_timestamp=" + before_timestamp;

        searchSite(post_url);
    }

}

module.exports = imgFlowGet;